﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Security.Permissions;

namespace Instalador
{
    public partial class Hijo2 : Form
    {
        public Hijo2()
        {
            InitializeComponent();
        }
        private void Hijo2_Shown(object sender, EventArgs e)
        {
            this.crearDirectorio();

            // Tendria que validar que la carpeta exista y sino crearla

            List<String> list = new List<String>();
            //WebClient webClient = new WebClient();
            //webClient.DownloadDataCompleted += new AsyncCompletedEventHandler(Completed);
            //webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
            //webClient.DownloadDataAsync(new Uri("http://bassart.com.ar/dist/"), @carpeta.Text+"/");

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(Padre.PATH_WEB_INSTALADOR_32);
            request.Method = WebRequestMethods.Ftp.ListDirectory;

            request.Credentials = new NetworkCredential(Padre.FTP_USUARIO, Padre.FTP_PASSWORD);

            StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream());

            string fileName = streamReader.ReadLine();
            while (fileName != null)
            {
                Console.WriteLine(fileName);
                if (fileName != "." && fileName != "..")
                    list.Add(fileName);
                fileName = streamReader.ReadLine();
            }
            request = null;
            streamReader = null;

            foreach (String file in list)
            {
                FtpWebRequest request2 = (FtpWebRequest)WebRequest.Create(Padre.PATH_WEB_INSTALADOR_32 + "//" + file);
                request2.Method = WebRequestMethods.Ftp.DownloadFile;
                request2.Credentials = new NetworkCredential(Padre.FTP_USUARIO, Padre.FTP_PASSWORD);
                FtpWebResponse response = (FtpWebResponse)request2.GetResponse();

                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream);

                FileStream writeStream = new FileStream(Padre.PATH_LOCAL_TEMP_INSTALADOR + "/" + file, FileMode.Create);
                int Length = 2048;
                Byte[] buffer = new Byte[Length];
                int bytesRead = responseStream.Read(buffer, 0, Length);
                int progress = bytesRead;
                fileDownload.Text = file;
                fileDownload.Refresh();

                while (bytesRead > 0)
                {
                    writeStream.Write(buffer, 0, bytesRead);
                    bytesRead = responseStream.Read(buffer, 0, Length);
                    if (progress - bytesRead >0)
                        progressBar.Value = ((progress-bytesRead) * 100) / progress;
                }
                writeStream.Close();
                response.Close();

                Console.WriteLine("Download Complete, status {0}", response.StatusDescription);
                reader.Close();
                response.Close();
            }
            Padre.PATH_LOCAL_TEMP_INSTALADOR = Padre.PATH_LOCAL_INSTALADOR + "\\temp";
        }
        [FileIOPermission(SecurityAction.Demand, Write = @"C:\Program Files")]
        private void crearDirectorio()
        {
            // Se crean los directorios necesarios para la instalación.

            // Se tiene que verificar si existe o no el directorio, en caso de que exista solamente deberiamos generar el temporal
            // si no existe tenemos que generar el temporal y tambien el del instalador.
            string newPath = null;

            if (System.IO.Directory.Exists(Padre.PATH_LOCAL_INSTALADOR))
            {
                // Se tiene que crear un subdirectorio temp y nada más.
                MessageBox.Show("existe el directorio se crea el subdirectorio");
                string activeDir = Padre.PATH_LOCAL_INSTALADOR;
                newPath = System.IO.Path.Combine(activeDir, "temp");

            }else {
                // Se tiene que crear el directorio de instalacion y el subdirectorio
                MessageBox.Show("No existe directorio ni sub");

            }

            try
            {
                System.IO.Directory.CreateDirectory(newPath);
            }
            catch (UnauthorizedAccessException esa)
            {
                MessageBox.Show("Usted no tiene permisos de acceso sobre la carpeta seleccionada");
            }

        }

        private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            progressBar.Value = e.ProgressPercentage;
        }

        private void Completed(object sender, AsyncCompletedEventArgs e)
        {
            MessageBox.Show("Download completed!");
        }
    }
}

